package com.qiye.livevideo.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.qiye.livevideo.common.CodeMsg;
import com.qiye.livevideo.common.ResultInfo;
import com.qiye.livevideo.model.Constant;
import com.qiye.livevideo.model.User;
import com.qiye.livevideo.service.UserService;
import com.qiye.livevideo.utils.EmptyUtils;
import com.qiye.livevideo.utils.WchartUtils;
import com.qiye.livevideo.utils.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: livevideo
 * @Date: 2019/5/3 9:37
 * @Author: tongling
 * @Description:
 */
@Api(description = "微信登录操作")
@RestController
public class WcharkController extends BaseController {

    @Resource
    private UserService userService;

    /**
     * 登录接口
     * @author Administrator
     * @param encryptedData
     * @param iv
     * @param code
     * @return
     */
    @ApiOperation(value = "微信登录")
    @GetMapping("/wChartLogin")
    public ResultInfo login(
            @RequestParam(value = "encryptedData", required = false) String encryptedData,
            @RequestParam(value = "iv", required = false) String iv,
            @RequestParam(value = "code", required = false) String code,
            @RequestParam(value = "sessionKey", required = false) String sessionKey
    ) {
        String openId = "";
        String unionId = "";
        String sessionkey = "";
        User userTemp;
        //code
        if (StringUtils.isBlank(sessionKey)) {
            System.out.println(code);
            JSONObject jsonObject = null;
            jsonObject = WchartUtils.getSessionKeyOropenid(code);
            unionId = jsonObject.getString("unionid");
            openId = jsonObject.getString("openid");
            String errcode = jsonObject.getString("errcode");
            sessionkey = jsonObject.getString("session_key");
            if (StringUtils.isNotBlank(errcode)) {
                if (errcode.equals(Constant.TWENTY_NINE)) {
                    return ResultInfo.error(CodeMsg.ERROR, "code无效！");
                }
                if (errcode.equals(Constant.SIXTY_THREE)) {
                    return ResultInfo.error(CodeMsg.ERROR, "code已被使用！");
                }
            }
            //是否第一次登录
            userTemp = userService.findUserByOpenId(openId);
            if (null == userTemp) {
                Map<String, String> map = new HashMap<>(3);
                map.put("sid", "");
                map.put("sessionkey", sessionkey);
                return ResultInfo.success(map, "首次登录！");
            } else {
                if (StringUtils.isNotBlank(unionId)) {
                    userTemp.setUnionId(unionId);
                }
                if (StringUtils.isNotBlank(openId)) {
                    userTemp.setOpenId(openId);
                }
            }
        } else {
            //解密获取用户信息
            JSONObject user = WchartUtils.getUserInfo(encryptedData, sessionKey, iv);

            unionId = user.getString("unionId");
            String phoneNumber = user.getString("phoneNumber");
            if (EmptyUtils.isNotEmpty(phoneNumber)) {
                return ResultInfo.success(phoneNumber, "获取手机号成功！");
            }
            openId = user.getString("openId");
            String nickName = user.getString("nickName");
            String city = user.getString("city");
            String province = user.getString("province");
            String country = user.getString("country");
            String gender = user.getString("gender");
            String avatarUrl = user.getString("avatarUrl");
            userTemp = userService.findUserByOpenId(openId);
            if (null == userTemp) {
                userTemp = new User();
            }
            if (StringUtils.isNotBlank(unionId)) {
                userTemp.setUnionId(unionId);
            }
            userTemp.setOpenId(openId);
            userTemp.setSex(Integer.valueOf(gender));
            userTemp.setNickName(nickName);
            userTemp.setCity(city);
            userTemp.setProvince(province);
            userTemp.setCountry(country);
            userTemp.setHeadImg(avatarUrl);

        }
        if (EmptyUtils.isEmpty(userTemp.getUserName())) {
            userTemp.setUserName(openId);
        }
        userTemp.setLastLoginTime(new Date());
        if (StringUtil.isEmpty(userTemp.getId())) {
            userTemp.setId(UUID());
            userTemp.setRegisterTime(new Date());
            userTemp.setRegisterIp(WebUtil.getInstance().getIpAddress());
            userService.insert(userTemp);
        } else {
            userService.update(userTemp);
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("sessionkey", sessionkey);
        return ResultInfo.success(map, "登录成功");

    }

}
